import React from 'react'
import TodoItem from './subpage'
import styles from './style.less'

export default class TodoList extends React.Component {

	constructor(props) {
		super(props)
		this.state = {
			list: ['React Todolist'],
			inputValue: ''
		}
		this.handleAdd = this.handleAdd.bind(this)
		this.handleInputChange = this.handleInputChange.bind(this)
		this.handleDelete = this.handleDelete.bind(this)
	}

	handleAdd(){
		if (this.state.inputValue === '') {
			return false
		}
		this.setState({
			list: [...this.state.list, this.state.inputValue],
			inputValue: ''
		})
	}
	handleInputChange(event){
		this.setState({
			inputValue: event.target.value
		})
	}
	handleDelete(index){
		const list = [...this.state.list]
		list.splice(index, 1)
		this.setState({
			list
		})
	}
	getTodoItem(){
		return (
			this.state.list.map((item,index) => {
				return (
					<TodoItem key={index} item={item} index={index} delete={this.handleDelete} />
				)
			})
		)
	}

	render() {
		return (
			<div>
				<div className={styles.adding}>
					<input type="text" placeholder='添加您的新任务' onChange={this.handleInputChange} value={this.state.inputValue}/>
					<button onClick={this.handleAdd}>添加任务</button>
				</div>
				<ul className={styles.list}>
					{this.getTodoItem()}
				</ul>
			</div>
		)
	}
}